const puppeteer = require('puppeteer');

module.exports = async (item) => {
  let is_valid_item = false;

  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 100,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-accelerated-2d-canvas',
      '--disable-gpu',
      '--window-size=1920x1080'
    ]
  });

  const page = await browser.newPage();
  await page.goto(item.url, {
    waitUntil: 'load'
  });

  const priceElement = await page.$('span.aok-offscreen');
  let price;

  // 如果当前商品有库存就会展示价格，没有价格就是没有商家在出售
  if (priceElement) {
    price = await page.evaluate(el => el.innerText, priceElement);
  } else {
    price = "JP¥9,900";
  }

  console.log(item.name, price)

  const price_num = Number(price.replace(/[^0-9]/ig, ""));

  if (price_num <= item.price) {
    console.log(`${item.name} 符合条件`);
    is_valid_item = true;
    // validArr.push(item);
  }

  await page.close();
  await browser.close();

  return is_valid_item ? item : null;
}